<template>
	<div>
		<el-row style="width: 80%; position: relative; top: 60px; margin: 0 auto">
			<!-- 搜索区域 -->
			<el-col :span="24">
				<el-form :inline="true" style="display: flex; justify-content: center">
					<el-form-item label-width="5px">
						<el-input v-model="name" clearable placeholder="输入章回名称" @clear="load" />
					</el-form-item>
					<el-form-item label-width="5px">
						<el-button type="primary" :icon="Search" @click="load"></el-button>
					</el-form-item>
				</el-form>
			</el-col>

			<!-- 卡片展示区域 -->
			<el-col :span="24">
				<div class="card-container">
					<el-row :gutter="20">
						<el-col v-for="item in tableData" :key="item.id" :span="8">
							<el-card class="card-item" shadow="hover" :body-style="{ padding: '0' }" @click="handleDetail(item.id)">
								<div class="image-container">
									<el-image :src="item.img" class="card-image" fit="contain" :preview-src-list="[item.img]" />
									<div class="image-overlay"></div>
								</div>
								<div class="card-content">
									<h3 class="card-title">
										<span class="title-text">{{ item.name }}</span>
									</h3>
								</div>
							</el-card>
						</el-col>
					</el-row>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
import { onBeforeUnmount, reactive, ref, shallowRef } from 'vue'
import { CircleCloseFilled, Close, Delete, Download, Edit, InfoFilled, Plus, Refresh, Search, Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import 'md-editor-v3/lib/style.css'
import UploadImage from '@/components/upload/upload-image/index.vue'
import { MdEditor } from 'md-editor-v3'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import router from '@/router'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const name = ref('')
const formSize = ref('default')
const ruleFormRef = ref()

const form = reactive({
	id: undefined,
	name: undefined,
	img: undefined,
	des: undefined,
	createTime: undefined,
	updateTime: undefined
})

// 表单校验规则
const rules = reactive({
	name: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	img: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	des: [{ required: true, message: '必选项不能为空', trigger: 'blur' }]
})

const handleDetail = id => {
	router.push(`/front/category/comment?id=${id}`)
}

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}

// 修改方法
const handleUpdate = async id => {
	dialogVisible.value = true
	headerTitle.value = reactive('编辑数据')
	const res = await request.get(`/category/${id}`)
	Object.assign(form, res.data)
}

// 单个删除方法
const handleDel = async id => {
	await request.delete(`/category/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}

const handleSilentClose = () => {
	handleResetForm(ruleFormRef.value)
	dialogVisible.value = false
}

// 批量删除方法
const handleBatchDel = async () => {
	const ids = []
	multipleSelection.value.forEach(row => {
		ids.push(row.id)
	})
	await request.delete(`/category/batch/${ids}`)
	ElMessage({
		showClose: true,
		message: '批量删除成功',
		type: 'success'
	})
	await load()
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/category/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			name: name.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
	tableData.value = res.data.records
}

// 加载页面初始化调用load方法
load()

// 清空查询数据重置方法
const handleReset = () => {
	name.value = ''
	load()
}

// 修改每页展示的数据量方法
const handleSizeChange = size => {
	pageSize.value = size
	load()
}

// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}

// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			await request({
				method: form.id ? 'put' : 'post',
				url: form.id ? `/category/${form.id}` : '/category',
				data: form
			})
			ElMessage({
				showClose: true,
				message: '操作成功',
				type: 'success'
			})
			await handleResetForm(formEl)
		} else {
			console.log('error submit!', fields)
		}
	})
}
// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/category/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}

// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/category/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}

// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		name: undefined,
		img: undefined,
		des: undefined,
		createTime: undefined,
		updateTime: undefined
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

// 文件上传方法
const uploadimg = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.img = res.data
	ruleFormRef.value.clearValidate('img')
}

// 文件下载
const dowload = async url => {
	window.open(url)
}

// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}
</script>

<style scoped lang="scss">
.card-container {
	padding: 20px 0;
}

.card-item {
	margin-bottom: 25px;
	border-radius: 12px;
	overflow: hidden;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
	border: 1px solid #ebeef5;

	&:hover {
		transform: translateY(-8px);
		box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);

		.image-overlay {
			opacity: 0.2;
		}

		.detail-icon {
			opacity: 1;
			transform: translateX(0);
		}
	}
}

.image-container {
	position: relative;
	overflow: hidden;
	border-radius: 8px 8px 0 0;
}

.image-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: linear-gradient(180deg, rgba(0, 0, 0, 0) 60%, rgba(0, 0, 0, 0.6) 100%);
	opacity: 0.4;
	transition: opacity 0.3s ease;
}

.card-image {
	width: 100%;
	height: 260px;
	transition: transform 0.3s ease;
}

.card-content {
	padding: 18px 20px;
	background: #ffffff;
}

.card-title {
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0;
	font-size: 18px;
	color: #303133;
	padding-right: 24px;

	.title-text {
		text-align: center;
		width: 100%;
	}

	.detail-icon {
		position: absolute;
		right: 0;
		color: #409eff;
		font-size: 20px;
		opacity: 0;
		transform: translateX(-10px);
		transition: all 0.3s ease;
	}
}

.card-description {
	font-size: 14px;
	color: #666;
	line-height: 1.5;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 3;
	-webkit-box-orient: vertical;
}

.pagination {
	margin-top: 30px;
	padding-bottom: 20px;

	:deep(.el-pagination) {
		justify-content: center;
	}
}

@media (max-width: 768px) {
	.card-item {
		margin-bottom: 15px;
	}

	.card-image {
		height: 200px;
	}

	.card-title {
		font-size: 16px;
	}
}
</style>
